/**
 * Created by tanbingqin on 2020/6/11.
 */
import React from 'react'
import { connect } from 'react-redux'
import { Button, Checkbox, Switch, Icon, Spin, Select, InputNumber, Input, Radio, Modal, Row, Col, TimePicker, message } from 'antd'
const RadioGroup = Radio.Group;
const Option = Select.Option;
import baseService from 'share/base.service'
import { messages, randomString } from 'share/common'
import moment from 'moment';
import Chooser from 'components/chooser'
import InputLanguage from 'components/template/input-language'
import processUtil from 'containers/setting/expense-type/new-expense-type/expense-type-travel/process-util'
import expenseTypeTravelService from 'containers/setting/expense-type/new-expense-type/expense-type-travel/expense-type-travel.service'
import errorMessage from 'share/errorMessage'
import CarConfigItem from 'containers/setting/expense-type/new-expense-type/expense-type-travel/comp/car-config-item'

class WidgetSetting extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      widget: {},
      loading: false,
      enumerationList: [],
    };
  }

  componentWillMount(){
    this.initEnum();
  };

  initEnum = () => {
    this.setState({loading: true});
    expenseTypeTravelService.getCustomEnumeration(0, 100).then(res => {
      this.setState({loading: false, enumerationList: res.data || []});
    }).catch(err => {
      this.setState({loading: false});
      errorMessage(err.response);
    });
  };

  componentDidMount(){
    const { widget } = this.props;
    this.updateWidget(widget);
  };

  componentWillReceiveProps(nextProps){
    const { widget } = nextProps;
    this.updateWidget(widget);
  }

  updateWidget = (newWidget) => {
    const { valueKey, onChange, languageList, language } = this.props;
    const { widget } = this.state;

    if (newWidget.messageKey && newWidget[valueKey] !== widget[valueKey]) {
      //新拖拽一个组件，或者切换选中组件
      if (newWidget.isNew) {
        //新拖拽的处理
        newWidget.isNew = undefined;

        //处理系统控件的多语言
        if (newWidget.type === 2001) {
          if (newWidget.messageKey === 'com_start_end_date') {
            let valueStart = messages('expense-6.key216')/*开始日期*/;
            let valueEnd = messages('common.end.date')/*结束日期*/;
            newWidget.fieldName = valueStart;
            newWidget.subFieldName = valueEnd;
            processUtil.initWidgetI18nByValue(newWidget, 'fieldNameI18n', valueStart, languageList, language);
            processUtil.initWidgetI18nByValue(newWidget, 'subFieldNameI18n', valueEnd, languageList, language);
          } else {
            processUtil.initWidgetI18nByKey(newWidget, 'fieldNameI18n', 'name', languageList, language);
            processUtil.initWidgetI18nByKey(newWidget, 'promptInfoI18n', 'promptInfo', languageList, language);
          }
          //处理必填默认值 处理只读默认值
          if (processUtil.isShowRequired(newWidget)) {
            let requiredConfig = this.getInitialValue('fieldConstraint', 'require', newWidget);
            newWidget.required = requiredConfig ? requiredConfig.value : false;
          }
          if (processUtil.isShowReadonly(newWidget)) {
            let isReadOnlyConfig = this.getInitialValue('fieldConstraint', 'isReadOnly', newWidget);
            newWidget.isReadOnly = isReadOnlyConfig ? isReadOnlyConfig.value : false;
          }
        }

        //处理套件控件的多语言
        if (newWidget.type === 2002) {
          newWidget.subWidgetList && newWidget.subWidgetList.forEach(subWidget => {
            if (subWidget.messageKey === 'com_start_end_date') {
              let valueStart = messages('expense-6.key216')/*开始日期*/;
              let valueEnd = messages('common.end.date')/*结束日期*/;
              subWidget.fieldName = valueStart;
              subWidget.subFieldName = valueEnd;
              processUtil.initWidgetI18nByValue(subWidget, 'fieldNameI18n', valueStart, languageList, language);
              processUtil.initWidgetI18nByValue(subWidget, 'subFieldNameI18n', valueEnd, languageList, language);
            } else {
              processUtil.initWidgetI18nByKey(subWidget, 'fieldNameI18n', 'name', languageList, language);
              processUtil.initWidgetI18nByKey(subWidget, 'promptInfoI18n', 'promptInfo', languageList, language);
            }

            //处理启用默认值 处理必填默认值 处理只读默认值
            if (processUtil.isShowValid(subWidget)) {
              let validConfig = this.getInitialValue('fieldConstraint', 'show', subWidget);
              subWidget.valid = validConfig ? validConfig.value : false;
            }
            if (processUtil.isShowRequired(subWidget)) {
              let requiredConfig = this.getInitialValue('fieldConstraint', 'require', subWidget);
              subWidget.required = requiredConfig ? requiredConfig.value : false;
            }
            if (processUtil.isShowReadonly(subWidget)) {
              let isReadOnlyConfig = this.getInitialValue('fieldConstraint', 'isReadOnly', subWidget);
              subWidget.isReadOnly = isReadOnlyConfig ? isReadOnlyConfig.value : false;
            }
          });
        }

        //处理控件一些配置的初始化值
        if (newWidget.messageKey === 'com_value_list') {
          //值列表默认单选
          newWidget.fieldContent = JSON.stringify({multiChoice: false});
        }
      } else {
        //切换选中的处理
      }
      onChange(newWidget);
      this.setState({widget: newWidget});
    }

    if (newWidget.messageKey && newWidget[valueKey] === widget[valueKey] && newWidget.isCombine && newWidget.subSelectedIndex !== widget.subSelectedIndex) {
      //在当前选中套件内切换子组件
      onChange(newWidget);
      this.setState({widget: newWidget});
    }

    if (!newWidget || !newWidget.messageKey) {
      this.setState({widget: {}});
    }
  };

  getWidgetTypeName = () => {
    const { widgetList } = this.props;
    const { widget } = this.state;
    let name = '';
    widgetList && widgetList.forEach(item => {
      if (item.messageKey === widget.messageKey) {
        name = item.name;
      }
    });
    return name;
  };

  //messageKey子组件的messageKey
  getSubWidgetTypeName = () => {
    const { widgetList } = this.props;
    const { widget } = this.state;
    let name = '';
    widgetList && widgetList.forEach(item => {
      if (item.messageKey === widget.messageKey) {
        let subWidgetList = item.subWidgetList || [];
        name = subWidgetList[widget.subSelectedIndex] && subWidgetList[widget.subSelectedIndex].name;
      }
    });
    return name;
  };

  handleLanguageInput = (value, attr) => {
    const { onChange } = this.props;
    let { widget } = this.state;
    let processWidget = this.getProcessWidget(widget);
    processWidget[attr] = value.name;
    processWidget[attr + 'I18n'] = value.i18n;
    onChange(widget);
    this.setState({widget});
  };

  //数字控件输入单位时的handle
  handleInputUnitValue = (value) => {
    const { onChange } = this.props;
    let { widget } = this.state;
    let processWidget = this.getProcessWidget(widget);
    processWidget.fieldContent = JSON.stringify({
      unit: value.name,
      unitI18n: processUtil.processLanguageToUpperCase(value.i18n)
    });
    onChange(widget);
    this.setState({widget});
  };

  handleChangeWidget = (value, key) => {
    const { onChange } = this.props;
    let { widget } = this.state;
    let processWidget = this.getProcessWidget(widget);
    processWidget[key] = value;
    if (key === 'isReadOnly' && processWidget.fieldConstraint) {
      let temp = JSON.parse(processWidget.fieldConstraint);
      temp.isReadOnly = {value: value, edit: true};
      processWidget.fieldConstraint = JSON.stringify(temp);
    }
    if (key === 'valid' && processWidget.fieldConstraint) {
      let temp = JSON.parse(processWidget.fieldConstraint);
      //没有processWidget.fieldConstraint，show,edit false,启用是禁用的不可更改
      temp.show = {value: value, edit: true};
      processWidget.fieldConstraint = JSON.stringify(temp);
    }
    if (key === 'required' && processWidget.fieldConstraint) {
      let temp = JSON.parse(processWidget.fieldConstraint);
      //没有processWidget.fieldConstraint，require,edit false,必填是禁用的不可更改
      temp.require = {value: value, edit: true};
      processWidget.fieldConstraint = JSON.stringify(temp);
    }
    onChange(widget);
    this.setState({widget});
  };

  //处理用车配置更改
  handleChangeCarAttr = (value, jsonName) => {
    const { onChange } = this.props;
    let { widget } = this.state;
    let processWidget = this.getProcessWidget(widget);
    processWidget[jsonName] = JSON.stringify(value);
    onChange(widget);
    this.setState({widget});
  };

  handleChangeAttr = (value, jsonName, attrName, messageKey) => {
    const { onChange } = this.props;
    let { widget } = this.state;
    let processWidget = this.getProcessWidget(widget);

    if (['com_remarks', 'com_text_area'].indexOf(messageKey) > -1 && typeof value === 'number') {
      if (value < 1) {
        value = 1;
      }
    }

    if(processWidget[jsonName]){
      let temp = JSON.parse(processWidget[jsonName]);
      temp[attrName] = value;
      processWidget[jsonName] = JSON.stringify(temp);
    } else {
      processWidget[jsonName] = JSON.stringify({[attrName]: value});
    }

    if (messageKey === 'com_start_end_date') {
      if(processWidget.subFieldConstraint){
        let temp = JSON.parse(processWidget.subFieldConstraint);
        temp[attrName] = value;
        processWidget.subFieldConstraint = JSON.stringify(temp);
      } else{
        processWidget.subFieldConstraint = JSON.stringify({[attrName]: value});
      }
    }

    onChange(widget);
    this.setState({widget});
  };

  getInitialValue = (jsonName, attrName, newWidget) => {
    let { widget } = this.state;
    let processWidget = newWidget || this.getProcessWidget(widget);
    return processWidget[jsonName] ? JSON.parse(processWidget[jsonName])[attrName] : null;
  };

  getProcessWidget = (widget) => {
    if (widget.isCombine) {
      return widget.subWidgetList[widget.subSelectedIndex];
    } else {
      return widget;
    }
  };

  renderTips = (type, widget, isCombine) => {
    let tips = '';
    let validMessageKeyList = ['com_start_end_date', 'com_departure_city', 'com_arrival_city', 'com_date', 'com_city'];
    if (type === 'valid' && validMessageKeyList.indexOf(widget.messageKey) > -1 && isCombine) {
      tips = messages('expense-6.key255')/*若表单为【差旅计划】填写模式时，若启用，默认不显示，从行程头取值*/;
    }
    return tips;
  };

  //如果是非套件，widget则是系统组件，如果是套件，widget则是子组件
  //isCombine为true表示widget组件是套件的子组件
  renderCustomWidget = (widget, isCombine) => {
    const { enumerationList } = this.state;
    switch(widget.messageKey) {
      case 'com_start_end_date':
        const formatOther = 'HH:mm';
        let isStartShowTime = widget.fieldConstraint && widget.fieldConstraint !== '' ? JSON.parse(widget.fieldConstraint).enableTime : false;
        let isEndShowTime = widget.subFieldConstraint && widget.subFieldConstraint !== '' ? JSON.parse(widget.subFieldConstraint).enableTime : false;
        let isAllShowTime = isStartShowTime && isEndShowTime;
        return <div />; //启用时间的配置先隐藏
        return isCombine ? <div /> : (
          <div>
            <div className="check-box-area margin-bottom-12">
              <Checkbox
                onChange={(e) => this.handleChangeAttr(e.target.checked, 'fieldConstraint', 'enableTime', 'com_start_end_date')}
                checked={isAllShowTime}>{messages('expense-6.key256')/*启用时间*/}
              </Checkbox>
            </div>
            {isAllShowTime && (
              <div>
                <Row className="check-box-area margin-bottom-12">
                  <Col span={8}>{messages('expense-6.key257')/*开始日期时间*/}:</Col>
                  <Col>
                    <TimePicker
                      value={this.getInitialValue('fieldConstraint', 'defaultTime') ? moment(this.getInitialValue('fieldConstraint', 'defaultTime')) : null}
                      allowEmpty={false}
                      format={formatOther}
                      onChange={(time) => this.handleChangeAttr(moment(time).second(0).utc().format(), 'fieldConstraint', 'defaultTime')}/>
                  </Col>
                </Row>
                <Row className="check-box-area margin-bottom-12">
                  <Col span={8}>{messages('expense-6.key258')/*结束日期时间*/}:</Col>
                  <Col>
                    <TimePicker
                      value={this.getInitialValue('subFieldConstraint', 'defaultTime') ? moment(this.getInitialValue('subFieldConstraint', 'defaultTime')) : null}
                      allowEmpty={false}
                      format={formatOther}
                      onChange={(time) => this.handleChangeAttr(moment(time).second(0).utc().format(), 'subFieldConstraint', 'defaultTime')}/>
                  </Col>
                </Row>
              </div>
            )}
          </div>
        );
      case 'com_number':
        return (
          <div>
            <div className="margin-bottom-12">
              <div className="form-title">{messages('expense-6.key259')/*整数位数*/}</div>
              <InputNumber
                max={15}
                min={1}
                precision={0}
                value={this.getInitialValue('fieldContent', 'integerMaxLength')}
                onChange={(value) => this.handleChangeAttr(value, 'fieldContent', 'integerMaxLength')}
              />
            </div>
            <div className="margin-bottom-12">
              <div className="form-title">{messages('expense-6.key260')/*小数位数*/}</div>
              <InputNumber
                max={10}
                min={0}
                precision={0}
                value={this.getInitialValue('fieldContent', 'decimalMaxLength')}
                onChange={(value) => this.handleChangeAttr(value, 'fieldContent', 'decimalMaxLength')}
              />
            </div>
            <div className="margin-bottom-12">
              <div className="form-title">{messages('common.unit')/*单位*/}</div>
              <InputLanguage
                onChange={value => this.handleInputUnitValue(value)}
                placeholder={messages('common.max.characters.length',{arg1: 100})/*最多输入{arg1}个字符*/}
                maxLength={100}
                value={{
                  name: this.getInitialValue('fieldContent', 'unit'),
                  i18n: this.getInitialValue('fieldContent', 'unitI18n') ? processUtil.processLanguageToLowerCase(this.getInitialValue('fieldContent', 'unitI18n')) : null
                }}
              />
            </div>
          </div>
        );
      case 'com_value_list':
        return (
          <div>
            <div className="radio-area margin-bottom-12">
              <RadioGroup
                onChange={(e) => this.handleChangeAttr(e.target.value, 'fieldContent', 'multiChoice')}
                value={!!this.getInitialValue('fieldContent', 'multiChoice')}
              >
                <Radio value={false}>{messages('expense-6.key261')/*单选*/}</Radio>
                <Radio value={true}>{messages('expense-6.key262')/*多选*/}</Radio>
              </RadioGroup>
            </div>
            <div className="margin-bottom-12">
              <div className="form-title">{messages('expense-6.key263')/*选择列表*/}</div>
              <Select
                onChange={(value) => this.handleChangeAttr(value, 'dataSource', 'customEnumerationOID')}
                value={this.getInitialValue('dataSource', 'customEnumerationOID')}
                getPopupContainer={triggerNode => triggerNode.parentNode}
              >
                {enumerationList.map(item => (
                  <Option key={item.customEnumerationOID}>{item.name}</Option>
                ))}
              </Select>
            </div>
          </div>
        );
      case 'com_remarks':
        return (
          <div className="margin-bottom-12">
            <div className="form-title">
              {messages('expense-6.key188')/*字符限制*/}&nbsp;&nbsp;&nbsp;
              <span style={{color: '#9BA2BB', fontSize: '12px'}}>
                {messages('expense-6.key264',{arg1: processUtil.getMaxLength(widget.messageKey)})/*支持输入1-{arg1}个字符*/}
              </span>
            </div>
            <div>
              <InputNumber
                placeholder={messages('common.please.input')/*请输入*/}
                max={processUtil.getMaxLength(widget.messageKey)}
                min={1}
                precision={0}
                step={1}
                value={this.getInitialValue('fieldContent', 'maxLength')}
                onChange={(value) => this.handleChangeAttr(value, 'fieldContent', 'maxLength', widget.messageKey)}
              />
            </div>
          </div>
        );
      case 'com_company_paid':
        return (
          <div>
            <div className="radio-area margin-bottom-12">
              <RadioGroup
                onChange={(e) => this.handleChangeAttr(e.target.value, 'fieldConstraint', 'turnOn')}
                value={!!this.getInitialValue('fieldConstraint', 'turnOn')}
              >
                <Radio value={true}>{messages('expense-6.key161')/*开启*/}</Radio>
                <Radio value={false}>{messages('expense-6.key160')/*关闭*/}</Radio>
              </RadioGroup>
            </div>
          </div>
        );
      case 'com_car':
        return <CarConfigItem widget={widget} onChange={(value) => this.handleChangeCarAttr(value, 'fieldConstraint')}/>
    }
  };

  //如果是非套件，widget则是系统组件，如果是套件，widget则是子组件
  //isCombine为true表示widget组件是套件的子组件
  renderWidget = (widget, isCombine) => {
    return widget ? (
      <div>
        {processUtil.isShowComponent(widget) && (
          <div className="margin-bottom-12">
            <div className="form-title">
              {widget.messageKey === 'com_start_end_date' ? messages('expense-6.key265')/*开始日期标题*/ : messages('expense-6.key153')/*标题*/}
            </div>
            <InputLanguage
              onChange={value => this.handleLanguageInput(value, 'fieldName')}
              placeholder={messages('common.max.characters.length',{arg1: 100})/*最多输入{arg1}个字符*/}
              maxLength={100}
              value={{
                name: widget.fieldName,
                i18n: widget.fieldNameI18n
              }}
            />
          </div>
        )}

        {!processUtil.isHidePrompt(widget) && (
          <div className="margin-bottom-12">
            <div className="form-title">{messages('expense-6.key100')/*提示文字*/}</div>
            <InputLanguage
              onChange={value => this.handleLanguageInput(value, 'promptInfo')}
              placeholder={messages('common.max.characters.length',{arg1: 100})/*最多输入{arg1}个字符*/}
              maxLength={100}
              value={{
                name: widget.promptInfo,
                i18n: widget.promptInfoI18n
              }}
            />
          </div>
        )}

        {widget.messageKey === 'com_prompt_text' && (
          <div className="margin-bottom-12">
            <div className="form-title">{messages('expense-6.key266')/*提示内容*/}</div>
            <InputLanguage
              onChange={value => this.handleLanguageInput(value, 'promptInfo')}
              placeholder={messages('common.max.characters.length',{arg1: 250})/*最多输入{arg1}个字符*/}
              maxLength={250}
              textArea
              value={{
                name: widget.promptInfo,
                i18n: widget.promptInfoI18n
              }}
            />
          </div>
        )}

        {processUtil.isShowComponent(widget) && (
          <div className="margin-bottom-12">
            <div className="form-title">
              {widget.messageKey === 'com_start_end_date' ? messages('expense-6.key267')/*开始日期控件编码*/ : messages('expense-6.key268')/*控件编码*/}
            </div>
            <Input
              placeholder={messages('common.please.input')/*请输入*/}
              value={widget.fieldCode}
              onChange={(e) => this.handleChangeWidget(e.target.value, 'fieldCode')}
            />
          </div>
        )}

        {widget.messageKey === 'com_start_end_date' && (
          <div>
            <div className="margin-bottom-12">
              <div className="form-title">
                {messages('expense-6.key269')/*结束日期标题*/}
              </div>
              <InputLanguage
                onChange={value => this.handleLanguageInput(value, 'subFieldName')}
                placeholder={messages('common.max.characters.length',{arg1: 100})/*最多输入{arg1}个字符*/}
                maxLength={100}
                value={{
                  name: widget.subFieldName,
                  i18n: widget.subFieldNameI18n
                }}
              />
            </div>
            <div className="margin-bottom-12">
              <div className="form-title">
                {messages('expense-6.key270')/*结束日期控件编码*/}
              </div>
              <Input
                placeholder={messages('common.please.input')/*请输入*/}
                value={widget.subFieldCode}
                onChange={(e) => this.handleChangeWidget(e.target.value, 'subFieldCode')}
              />
            </div>
          </div>
        )}

        <div className="check-box-area margin-bottom-12">
          {processUtil.isShowReadonly(widget) && (
            <Checkbox
              onChange={(e) => this.handleChangeWidget(e.target.checked, 'isReadOnly')}
              disabled={this.getInitialValue('fieldConstraint', 'isReadOnly') ? !this.getInitialValue('fieldConstraint', 'isReadOnly').edit : false}
              checked={this.getInitialValue('fieldConstraint', 'isReadOnly') ? this.getInitialValue('fieldConstraint', 'isReadOnly').value : false}>
              {messages('expense-6.key271')/*只读*/}
            </Checkbox>
          )}
          {/*套件子组件才有配置启用*/}
          {isCombine && processUtil.isShowValid(widget) && (
            <Checkbox
              onChange={(e) => this.handleChangeWidget(e.target.checked, 'valid')}
              disabled={this.getInitialValue('fieldConstraint', 'show') ? !this.getInitialValue('fieldConstraint', 'show').edit : true}
              checked={this.getInitialValue('fieldConstraint', 'show') ? this.getInitialValue('fieldConstraint', 'show').value : false}>
              {messages('expense-6.key233')/*启用temp*/}
              <span className="default-span">
                {this.renderTips('valid', widget, isCombine)}
              </span>
            </Checkbox>
          )}
          {processUtil.isShowRequired(widget) && (
            <Checkbox
              onChange={(e) => this.handleChangeWidget(e.target.checked, 'required')}
              disabled={this.getInitialValue('fieldConstraint', 'require') ? !this.getInitialValue('fieldConstraint', 'require').edit : true}
              checked={this.getInitialValue('fieldConstraint', 'require') ? this.getInitialValue('fieldConstraint', 'require').value : false}>
              {messages('expense-6.key168')/*必填*/}
            </Checkbox>
          )}
          {processUtil.isShowHide(widget) && (
            <Checkbox
              onChange={(e) => this.handleChangeWidget(e.target.checked, 'hide')}
              checked={widget.hide}>
              {messages('expense-6.key272')/*隐藏*/}
            </Checkbox>
          )}
        </div>

        {this.renderCustomWidget(widget, isCombine)}
      </div>
    ) : <div/>
  };

  render() {
    const { widget, loading } = this.state;
    return (
      <div className="widget-setting-block">
        {widget && widget.messageKey && (
          <div>
            {widget.isCombine && (
              <div className="form-title margin-bottom-12">
                {messages('expense-6.key244')/*默认套件*/}：{this.getWidgetTypeName()}
              </div>
            )}
            <div className="form-title margin-bottom-12">
              {messages('expense-6.key273')/*控件类型*/}：{widget.isCombine ? this.getSubWidgetTypeName() : this.getWidgetTypeName()}
            </div>

            {loading ? <Spin/> : this.renderWidget(this.getProcessWidget(widget), widget.isCombine)}
          </div>
        )}
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    language: state.main.language,
    languageList: state.login.languageList,
  }
}

WidgetSetting.propTypes = {
  valueKey: React.PropTypes.string,  //key值属性，用于检查不同组件切换的flag
  nowWidgetList: React.PropTypes.array, //当前所选的所有控件
  widget: React.PropTypes.object,  //控件对象
  onChange: React.PropTypes.func,  //更改属性时的回调
  widgetList: React.PropTypes.array,  //控件列表，如果需要显示控件类型则必填
};

WidgetSetting.defaultProps = {
  valueKey: '',
  nowWidgetList: [],
  widget: {},
  onChange: () => {},
  widgetList: [],
};

export default connect(mapStateToProps)(WidgetSetting)
